<template>
  <div class="info-left">
<!--    <div class="info-head">-->
<!--      <div class="pdf-title">合同信息</div>-->
<!--      <div  class="pdf-info-btn">-->
<!--        <a-button type="link" @click="editClick">-->
<!--          <template #icon>-->
<!--            <EditOutlined />-->
<!--          </template>-->
<!--          编辑-->
<!--        </a-button>-->
<!--        <a-button :style="{margin: '0 10px'}" type="link" v-if="isEdit" @click="saveClick">-->
<!--          保存-->
<!--        </a-button>-->
<!--        <a-button type="link" v-if="isEdit" @click="cancelClick">-->
<!--          取消-->
<!--        </a-button>-->
<!--      </div>-->
<!--    </div>-->
    <div class="descriptions-box">
      <a-descriptions :column="1" :labelStyle="labelStyle">
        <a-descriptions-item label="合同名称">
          <span  @click="searchPostion(formState.contractName)"> {{formState.contractName}}</span>
        </a-descriptions-item>
        <a-descriptions-item label="合同编号">
          <span> {{formState.contractNumber}}</span>
        </a-descriptions-item>
        <a-descriptions-item label="补充合同原件" v-if="formState.status === 1">
          <a-button @click="showFileModel" class="border-btn">
            <template #icon>
              <UploadOutlined/>
            </template>
            点击上传
          </a-button>
        </a-descriptions-item>
        <a-descriptions-item label="贸易主体">
          <a-select v-if="isEdit" :style="{width: '100%'}" v-model:value="formState.tradeBody" placeholder="请选择贸易主体" :options="tradeareas" />
          <span v-else>
            <span v-for="item in tradeareas" :key="item.label">
              <span v-if="item.value === formState.tradeBody">{{item.label}}</span>
            </span>
            </span>
        </a-descriptions-item>
        <a-descriptions-item label="合同签订日期">
          <a-date-picker v-if="isEdit" :style="{width: '100%'}" v-model:value="formState['signingDate']"  value-format="YYYY-MM-DD" />
          <span v-else> {{formState.signingDate}}</span>
        </a-descriptions-item>
<!--        <a-descriptions-item label="全年/合同预计额">-->
<!--          <a-input-number v-if="isEdit" v-model:value="formState.expectedAmount" :style="{width: '100%'}" placeholder="请输入合同累计价格"  :min="1" >-->
<!--            <template #addonAfter>-->
<!--              <a-select  style="width: 100px" v-model:value="formState.currency">-->
<!--                <a-select-option :value="1">美元</a-select-option>-->
<!--                <a-select-option :value="2">人民币</a-select-option>-->
<!--                <a-select-option :value="3">欧元</a-select-option>-->
<!--              </a-select>-->
<!--            </template>-->
<!--          </a-input-number>-->
<!--          <span v-else>-->
<!--            <span>{{formState.expectedAmountStr}}</span>-->
<!--&lt;!&ndash;                  <span v-for="item in moneyAreas" :key="item.label">&ndash;&gt;-->
<!--&lt;!&ndash;                    <span v-if="item.value === formState.currency && formState.expectedAmount">{{formState.expectedAmount}}&nbsp;{{item.label}}  </span>&ndash;&gt;-->
<!--&lt;!&ndash;                  </span>&ndash;&gt;-->
<!--          </span>-->
<!--        </a-descriptions-item>-->
        <a-descriptions-item label="服务期限">
          <a-input-number  v-if="isEdit" v-model:value="formState.servicePeriod"  :style="{width: '100%'}" placeholder="请输入服务期限" :min="1" >
            <template #addonAfter>
              <div class="numAfter">年</div>
            </template>
          </a-input-number>
          <span v-else> {{formState.servicePeriod? `${formState.servicePeriod}年` : ''}}</span>
        </a-descriptions-item>
        <a-descriptions-item label="预计全年/合同的保险费">
          <a-input-number v-if="isEdit" v-model:value="formState.expectedInsurancePrice" :style="{width: '100%'}" placeholder="请输入合同累计价格"  :min="1" >
            <template #addonAfter>
              <a-select  style="width: 100px" v-model:value="formState.currency">
                <a-select-option :value="1">美元</a-select-option>
                <a-select-option :value="2">人民币</a-select-option>
                <a-select-option :value="3">欧元</a-select-option>
              </a-select>
            </template>
          </a-input-number>
          <span v-else>
            <span>{{formState.expectedInsurancePriceStr}}</span>
<!--              <span v-for="item in moneyAreas" :key="item.label">-->
<!--                <span v-if="item.value === formState.currency && formState.expectedInsurancePrice">{{formState.expectedInsurancePrice}} &nbsp; {{item.label}}</span>-->
<!--            </span>-->
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="保险费率">
          <a-input-number v-if="isEdit"
                          :min="0"
                          :max="100"
                          placeholder="请输入"
                          :style="{width: '100%'}"
                          v-model:value="formState.priceRate"
          >
            <template #addonAfter>
              <div class="numAfter">%</div>
            </template>
          </a-input-number>
          <span v-else> {{formState.priceRateStr}}</span>
        </a-descriptions-item>
        <a-descriptions-item label="到期时间">
          <a-date-picker v-if="isEdit" :style="{width: '100%'}" v-model:value="formState['expirationDate']"  value-format="YYYY-MM-DD" />
          <span v-else> {{formState.expirationDate}}</span>
        </a-descriptions-item>
        <a-descriptions-item label="支付时间">
          <a-input-number v-if="isEdit" :style="{width: '100%'}" v-model:value="formState.payDays" placeholder="请输入支付时间"  :min="1">
            <template #addonAfter>
              <a-select  style="width: 100px" v-model:value="formState.payDaysType">
                <a-select-option :value="1">工作日</a-select-option>
                <a-select-option :value="2">自然日</a-select-option>
              </a-select>
            </template>
          </a-input-number>
          <span v-else> {{formState.payDays}}
                <span v-for="item in dateTypeAreas" :key="item.label">
                  <span v-if="item.value === formState.payDaysType">{{item.label}}</span>
                </span>
                </span>
        </a-descriptions-item>
        <a-descriptions-item label="合同状态">
          <a-select v-if="isEdit" :style="{width: '100%'}" v-model:value="formState.status" placeholder="请选择合同状态" :options="contractType" />
          <span v-else  :style="{color: '#0062AD',  cursor: 'pointer'}">
                        <span v-for="item in contractType" :key="item.label">
                     <span v-if="item.value === formState.status">{{item.label}}</span>
                </span>
                </span>
        </a-descriptions-item>
        <a-descriptions-item label="合同上传时间">
          <span> {{formState.createDate}}</span>
        </a-descriptions-item>
        <a-descriptions-item label="创建者">
          <span> {{formState.createBy}}</span>
        </a-descriptions-item>
      </a-descriptions>
    </div>
    <!--  合同原件上传   -->
    <a-modal v-model:visible="fileVisible" :width="600" title="补充合同原件"  @ok="handleFileChange">
      <a-form :model="suppFileForm" labelAlign="left">
        <a-form-item name="dragger" no-style>
          <a-upload-dragger
              v-model:fileList="contractFileList"
              :action="fileAction"
              :beforeUpload="fileBeforeUpload"
              @change="postSuppFile"
              name="file"
              accept=".pdf"
          >
            <div class="dragger-img">
              <img src="@/assets/images/ResourceContract/file.png" alt="">
            </div>
            <p class="ant-upload-text" :style="{color: '#2C3749',fontSize: '14px'}">将文件拖到此处，或 <span :style="{color: '#0062AD'}">点击上传</span> </p>
            <p class="ant-upload-hint" :style="{color: '#6B7A8B', fontSize: '12px'}" >支持pdf</p>
          </a-upload-dragger>
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="from-btn-right">
          <a-button key="back" class="border-btn" @click="colseFileModel">取消</a-button>
          <a-button key="submit" @click="handleFileChange" class="search-btn1">保存</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import {defineEmits, defineProps, getCurrentInstance, reactive, ref, watch} from "vue";
import { EditOutlined, UploadOutlined } from '@ant-design/icons-vue';
import {BASE_URL} from "@/config/proxyIp";
import {message} from "ant-design-vue";
const { proxy  } = getCurrentInstance()
const emit = defineEmits(['searchTxt', 'saveEdit'])
const isEdit = ref(false)
const isSave = ref(false)
const formState = ref({
  contractName: '', // 合同名称
  contractNumber: '', // 合同编号
  tradeBody: '', // 贸易主体(国贸、新贸)
  signingDate: '', // 签订日期
  assured: '', // 被保险人
  insurer: '', // 承保人
  targetAndType: '', // 保险标的及类别
  expectedAmount: '', // 全年/合同预计额
  currency: '', // 币种
  servicePeriod: '', // 服务期限(单位年)
  price: '', // 保险费
  priceRate: '', // 保险费率
  expirationDate: '', // 到期时间
  payDays: '', // 支付时间（天）
  payDaysType: '', // 支付时间（天）类型，自然日/工作日
  createDate: '', // 创建时间
  createBy: '', // 创建人
  id: '',
  status: '',
  expectedAmountStr: '',
  expectedInsurancePriceStr: '',
  priceRateStr: '',
  expectedInsurancePrice: '' // 预计保险费
})
const props = defineProps({
  dataObj: {
    type: Object,
    required: true,
    default: () =>  {}
  },
  isEdits: {
    type: Boolean,
    required: true,
    default: () =>  false
  },
  isSaves: {
    type: Boolean,
    required: true,
    default: () =>  false
  }
})
watch(() => props.dataObj, (newVal) => {
  console.log('传过来的详情更新了没', newVal)
  formState.value = newVal
})
watch(() => props.isSaves, (newVal) => {
      isSave.value = newVal
      if (newVal) {
        saveClick()
      }
    },
    {
      deep:  true
    }
)
watch(() => props.isEdits, (newVal) => {
  isEdit.value = newVal
}, {
  deep:  true
})
const moneyAreas = ref([
  {
    label: '美元',
    value: 1
  },
  {
    label: '人民币',
    value: 2
  },
  {
    label: '欧元',
    value: 3
  },
])
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
  {
    label: '国贸&新贸',
    value: 3
  },
])
// 工作日的类型
const dateTypeAreas = ref([
  {
    label: '工作日',
    value: 1
  },
  {
    label: '自然日',
    value: 2
  }
])
// 合同状态
const contractType = ref([
  {
    label: '草稿',
    value: 1
  },
  {
    label: '已签订',
    value: 2
  },
  {
    label: '执行中',
    value: 3
  },
  {
    label: '已完成',
    value: 4
  },
  {
    label: '暂停中',
    value: 5
  }
])
const labelStyle = ref({
  color: '#6B7A8B'
})
// const editClick = () => {
//   isEdit.value = true
//   isSave.value = false
// }
const saveClick = () => {
  proxy.$api.putCargoInsurance(formState.value).then(res => {
    console.log('修改成功', res)
    isEdit.value = false
    isSave.value = true
    emit('saveEdit', isSave.value)
  })

}
// const cancelClick = () => {
//   isEdit.value = false
//   isSave.value = true
// }
const searchPostion = (txt) => {
  console.log('要搜索的文字', txt)
  emit('searchTxt', txt)
}
/**
 * 补充合同原件
 * */
const contractFileList = ref([])
const fileAction = ref(`${BASE_URL}/con/common/upload`)
const fileVisible = ref(false)
const suppFileForm = reactive({
  conId: formState.value.id.toString(),
  url: ''
})
const colseFileModel = () => {
  fileVisible.value = false
}
const showFileModel = () => {
  fileVisible.value = true
  contractFileList.value = []
}
const postSuppFile = (info) => {
  const status = info.file.status
  if (status === 'done') {
    suppFileForm.url = info.file.response.resultObject
  } else if (status === 'error') {
    message.error(`${info.file.name} 文件上传失败`);
  }
}
const fileBeforeUpload = (file) => {
  let houzui = file.name.substring(file.name.lastIndexOf('.'), file.name.length).toLowerCase()
  let res = ['.pdf'].includes(houzui)
  if (!res) {
    contractFileList.value = []
    message.error('请上传PDF文件')
  }
  return res
}
const handleFileChange = () => {
  Object.assign(suppFileForm, {
    conId: formState.value.id.toString()
  })
  proxy.$api.supppleContract(suppFileForm).then(res => {
    if (res.resultCode === 0) {
      fileVisible.value = false
      isSave.value = true
      message.success('合同原件上传成功')
      emit('saveEdit', isSave.value)
    }
  })
}
// 合同状态更改
watch(() => formState.value.status, (val) => {
  if (val > 1) {
    contractType.value.map(item => {
      if (item.value === 1) {
        Object.assign(item, {
          disabled: true
        })
      }
    })
  }
  if (val === 3) {
    contractType.value.map(item => {
      if (item.value < 3) {
        Object.assign(item, {
          disabled: true
        })
      }
      if (item.value > 3) {
        Object.assign(item, {
          disabled: false
        })
      }
    })
  }
  if (val === 4) {
    contractType.value.map(item => {
      if (item.value < 4) {
        Object.assign(item, {
          disabled: true
        })
      }
      if (item.value === 5) {
        Object.assign(item, {
          disabled: true
        })
      }
    })
  }
  if (val === 5) {
    contractType.value.map(item => {
      if (item.value === 1) {
        Object.assign(item, {
          disabled: true
        })
      }
      if (item.value === 2) {
        Object.assign(item, {
          disabled: true
        })
      }
      if (item.value === 3) {
        Object.assign(item, {
          disabled: false
        })
      }
      if (item.value === 4) {
        Object.assign(item, {
          disabled: false
        })
      }
    })
  }
})
</script>

<style lang="scss" scoped>
.info-left {
  padding: 24px;
  background: #ffffff;
  border-radius: 4px;
  height: 100%;
  .info-head {
    display: flex;
    justify-content: space-between;
  }
  .descriptions-box {
    overflow-y: scroll;
    height: 95%;
  }
}
.pdf-title {
  font-size: 20px;
  font-weight: bold;
  text-align: left;
  color: #2c3749;
  line-height: 28px;
  margin-bottom: 24px;
}
</style>
